package cn.wjdiankong.levideo.list.adapter;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.ss.android.common.applog.GlobalContext;

import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.TextView;
import cn.wjdiankong.levideo.R;
import cn.wjdiankong.levideo.activity.VideoPlayerActivity;
import cn.wjdiankong.levideo.data.LevideoData;
import cn.wjdiankong.levideo.database.LocalStorage;
import cn.wjdiankong.levideo.dialog.VideoInfoDialog;
import cn.wjdiankong.levideo.dialog.VideoLongClickPopupMenu;
import cn.wjdiankong.levideo.dialog.VideoLongClickPopupMenu.MenuClickItemListener;
import cn.wjdiankong.levideo.utils.Const;
import cn.wjdiankong.levideo.utils.ImageLoaderUtils;
import cn.wjdiankong.levideo.utils.NetworkUtil;
import cn.wjdiankong.levideo.utils.UIUtil;
import cn.wjdiankong.levideo.utils.UmengReportUtils;
import cn.wjdiankong.levideo.utils.Utils;
import cn.wjdiankong.levideo.view.listview.ArrayAdapter;

public abstract class BaseFragmentListAdapter extends ArrayAdapter<Integer>{
	
	protected List<LevideoData> dataList = new ArrayList<LevideoData>();
	protected Context mContext;
	protected VideoLongClickPopupMenu menu;
	protected VideoInfoDialog infoDialog;
	protected AbsListView mListView;
	
	protected ImageLoader imageLoader = null;
	protected DisplayImageOptions userIconOptions, imgOptions, musicOptions;
	protected boolean isLocal;
	
	public BaseFragmentListAdapter(Context ctx, AbsListView listView, boolean isLocal){
		mContext = ctx;
		mListView = listView;
		imageLoader = ImageLoaderUtils.getInstance(ctx).getImageLoader();
		userIconOptions = new DisplayImageOptions.Builder()
				.cacheInMemory(true)
				.cacheOnDisc(true)
				.showImageOnFail(R.drawable.user_icon_zhanwei)
				.build();
		imgOptions = new DisplayImageOptions.Builder()
				.cacheInMemory(true)
				.cacheOnDisc(true)
				.build();
		this.isLocal = isLocal;
	}

	public void setListView(AbsListView listView){
		mListView = listView;
	}

	public void setAfterDataList(List<LevideoData> dataList){
		if(dataList != null && dataList.size() > 0){
			this.dataList.addAll(dataList);
			notifyDataSetChanged();
		}
	}
	
	public void setBeforeDataList(List<LevideoData> dataList){
		if(dataList != null && dataList.size() > 0){
			this.dataList.addAll(0, dataList);
			notifyDataSetChanged();
		}
	}
	
	public List<LevideoData> getDataList(){
		return dataList;
	}
	
	public void removeData(LevideoData data){
		if(dataList != null && dataList.size() > 0){
			dataList.remove(data);
			notifyDataSetChanged();
		}
	}
	
	public void removeData(int position){
		if(dataList != null && dataList.size() > 0 && position < dataList.size()){
			dataList.remove(position);
			notifyDataSetChanged();
		}
	}
	
	public boolean isNoData(){
		return dataList == null || dataList.size() == 0;
	}
	
	public LevideoData getVideoData(int pos){
		if(dataList != null && dataList.size() > 0 && pos < dataList.size()){
			return dataList.get(pos);
		}
		return null;
	}
	
	@Override
	public int getCount() {
		return dataList.size();
	}
	
	protected abstract int getLayoutId();
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
	    ViewHolder viewHolder;
		View view = convertView;
		if (view == null || view.getTag() == null) {
			view = LayoutInflater.from(mContext).inflate(getLayoutId(), parent, false);
			viewHolder = new ViewHolder();
			viewHolder.textV = (TextView) view.findViewById(R.id.content_txt);
			viewHolder.imgV = (ImageView) view.findViewById(R.id.content_img);
			viewHolder.loadingView = view.findViewById(R.id.loadView);
			viewHolder.userIcon = (ImageView)view.findViewById(R.id.user_icon);
			viewHolder.userName = (TextView)view.findViewById(R.id.user_name);
			viewHolder.timeTxt = (TextView)view.findViewById(R.id.time_txt);
			viewHolder.playIcon = view.findViewById(R.id.play_icon);
			viewHolder.broseCountTxt = (TextView)view.findViewById(R.id.play_count_txt);
			viewHolder.broseCountView = view.findViewById(R.id.play_count_layout);
			viewHolder.saveTimeLayout = view.findViewById(R.id.savetime_layout);
			viewHolder.saveTimeTxt = (TextView)view.findViewById(R.id.savetime_txt);
			view.setTag(viewHolder);
		} else {
			viewHolder = (ViewHolder) view.getTag();
		}
		
		viewHolder.textV.setText(dataList.get(position).title);
		if(isLocal){
			viewHolder.userName.setVisibility(View.GONE);
		}else{
			viewHolder.userName.setVisibility(View.VISIBLE);
		}
		if(TextUtils.isEmpty(dataList.get(position).authorName)){
			viewHolder.userName.setText("昵称加载中...");
		}else{
			viewHolder.userName.setText(dataList.get(position).authorName);
		}
		
		if(!TextUtils.isEmpty(dataList.get(position).formatTimeStr)){
			viewHolder.timeTxt.setText("发布于: "+dataList.get(position).formatTimeStr);
			viewHolder.timeTxt.setVisibility(View.VISIBLE);
		}else{
			viewHolder.timeTxt.setVisibility(View.GONE);
		}
		
		if(!TextUtils.isEmpty(dataList.get(position).formatPlayCountStr)){
			viewHolder.broseCountTxt.setText(dataList.get(position).formatPlayCountStr+"人观看");
			viewHolder.broseCountView.setVisibility(View.VISIBLE);
		}else{
			viewHolder.broseCountView.setVisibility(View.GONE);
		}
		
		if(!TextUtils.isEmpty(dataList.get(position).coverImgUrl)){
			imageLoader.displayImage(dataList.get(position).coverImgUrl, viewHolder.imgV, imgOptions);
		}
		if(!TextUtils.isEmpty(dataList.get(position).authorImgUrl)){
			imageLoader.displayImage(dataList.get(position).authorImgUrl, viewHolder.userIcon, userIconOptions);
		}
		
		if(isLocal){
			viewHolder.saveTimeLayout.setVisibility(View.VISIBLE);
			viewHolder.saveTimeTxt.setText("保存于: "+Utils.formatTimeStr(dataList.get(position).createTime));
		}else{
			viewHolder.saveTimeLayout.setVisibility(View.GONE);
		}
		
		ClickItemListener listener = new ClickItemListener(position);
		view.setOnClickListener(listener);
		if(isLocal){
			view.setOnLongClickListener(listener);
		}
		
		return view;
		
	}
	
	public static class ViewHolder{
		public TextView textV;//标题
		public ImageView imgV;//封面图
		public ImageView userIcon;//用户图
		public TextView userName;//用户名称
		public TextView timeTxt;//时间
		public View loadingView;//加载图
		public View playIcon;//播放按钮
		public TextView broseCountTxt;//观看人数
		public View broseCountView;//播放人数视图
		
		//火山视频
		public TextView cityTxt;
		
		//抖音
		public ImageView musicImg;
		public TextView musicTxt;
		public View musicLayout;
		
		//秒拍
		public TextView durationTimeTxt;
		
		public View saveTimeLayout;
		public TextView saveTimeTxt;
	}
	
	private class ClickItemListener implements OnClickListener, OnLongClickListener{

		private int curPosition = 0;
		
		public ClickItemListener(int pos){
			curPosition = pos;
		}
		
		@Override
		public boolean onLongClick(View view) {
			int type = getVideoType();
			final HashMap<String, String> params = new HashMap<String, String>();
			params.put("video_source", Utils.getVideoTypeStr(type));
			UmengReportUtils.report(UmengReportUtils.LOCALVIDEO_MENU, params);
			final LevideoData data = getVideoData(curPosition);
			if(menu == null){
				menu = new VideoLongClickPopupMenu((Activity)mContext);
			}
			menu.setMenuShowAnchorView(view, mListView, curPosition);
			menu.setOneScreen(type == Const.VIDEO_TYPE_MIAOPAI);
			menu.setMenuClickItemListener(new MenuClickItemListener() {
				@Override
				public void clickItem(int type) {
					if(type == MenuClickItemListener.DELETE_VIDEO){
						UmengReportUtils.report(UmengReportUtils.LOCALVIDEO_DELETE, params);
						//对于头条视频，数据库中的保存数据和firstVideoPlayUrl值就是一样的。
						boolean isSucc = LocalStorage.getInstance().deleteLevideoData(data.videoPlayUrl);
						if(isSucc){
							File file = new File(data.videoPlayUrl);
							if(file.exists()){
								isSucc = file.delete();
								if(isSucc){
									removeData(data);
									UIUtil.showShortHintToast(GlobalContext.getContext(), "删除成功");
								}
							}
						}
					}else if(type == MenuClickItemListener.DETAIL_VIDEO){
						UmengReportUtils.report(UmengReportUtils.LOCALVIDEO_DETAIL, params);
						if(infoDialog == null){
							infoDialog = new VideoInfoDialog((Activity)mContext);
						}
						infoDialog.setLevideoData(data);
						infoDialog.show();
					}
				}
			});
			menu.toggleMenu();
			return true;
		}

		@Override
		public void onClick(View v) {
			LevideoData data = getVideoData(curPosition);
			if(data != null){
				int type = getVideoType();
				if(isLocal){
					VideoPlayerActivity.startDefaultResult((Activity)mContext, (ArrayList<LevideoData>)getDataList(), curPosition, type, isLocal);
				}else{
					if(!NetworkUtil.isNetworkAvailable(mContext)){
						UIUtil.showShortHintToast(mContext, "网络不可用，请检查网络重试！");
						return;
					}
					VideoPlayerActivity.startDefault(mContext, (ArrayList<LevideoData>)getDataList(), curPosition, type, isLocal);
				}
			}
		}
		
	}
	
	private int getVideoType(){
		int type = -1;
		switch(getLayoutId()){
			case R.layout.fragment_douyin_adapter_item_layout:
				type = Const.VIDEO_TYPE_DOUYIN;
				break;
			case R.layout.fragment_huoshan_adapter_item_layout:
				type = Const.VIDEO_TYPE_HUOSHAN;
				break;
			case R.layout.fragment_kuaishou_adapter_item_layout:
				type = Const.VIDEO_TYPE_KUAISHOU;
				break;
			case R.layout.fragment_miaopai_adapter_item_layout:
				type = Const.VIDEO_TYPE_MIAOPAI;
				break;
		}
		return type;
	}
	
}
